<template>
  <div class="customer-brand">
    <div class="left">
      <a-spin :spinning="spinning" class="spin-box">
        <a-row justify="space-between" align="middle" class="padding-5">
          <a-col>品牌业态</a-col>
          <a-col>
            <a-button
              type="text"
              @click="addBrand"
              size="small"
              :disabled="!isCategoryAdd"
            >
              <plus-outlined class="plus-outlined" />
            </a-button>
          </a-col>
        </a-row>
        <a-divider class="divider" />
        <div class="tree-content hide-scroller-bar padding-5">
          <a-tree
            v-model:selectedKeys="selectedKeys"
            :tree-data="treeData"
            block-node
            :selectable="true"
            @select="onSelect"
            :fieldNames="fieldNames"
          >
            <template #title="{ cat_name, id }">
              <a-row justify="space-between item-content">
                <a-col>{{ cat_name }}</a-col>
                <a-col class="ellipsis" v-if="id">
                  <a-dropdown>
                    <ellipsis-outlined />
                    <template #overlay>
                      <a-menu>
                        <a-menu-item
                          style="padding: 5px 30px"
                          :disabled="!isCategoryEdit"
                          @click="menuClick(id, 'edit')"
                        >
                          编辑
                        </a-menu-item>
                        <a-menu-item
                          style="padding: 5px 30px; color: red"
                          :disabled="!isCategoryDelete"
                          @click="menuClick({ cat_name, id }, 'delete')"
                        >
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </a-col>
              </a-row>
            </template>
          </a-tree>
          <a-empty v-if="!treeData.length" :image="simpleImage" />
        </div>
      </a-spin>
    </div>
    <div ref="rightRef" class="right">
      <CustomTable
        ref="customTableRef"
        :columns="columns"
        :hasPagination="true"
        :requestInfo="{
          service: '/org', // 请求服务
          serviceUrl: '/org/brand/custom/brand/query', // 请求url
          serviceType: 'post', // 请求方式
        }"
        :extraParams="{
          filters: filters,
        }"
        titleName="品牌列表"
        :tableHeight="tableHeight"
        :exportTitle="exportTitle"
        :rightButtons="rightButtons"
        :tableConfig="$store.getters.tableConfig"
        :excludeImport="true"
        tableId="CustomerBrandList"
        @request="$utils.commonRequest"
        :customRow="customRow"
      >
        <template #buttonIcon-add_brand>
          <PlusOutlined />
        </template>
      </CustomTable>
    </div>

    <!-- 添加品牌分类 -->
    <AddBrandCategory
      :visible="visiblBrandeCategory"
      :id="brandeId"
      @success="successChange"
      @close="visiblBrandeCategory = false"
    />

    <!-- 添加品牌 -->
    <AddBrand
      :visible="visiblBrande"
      :id="detailId"
      @success="successBrandChange"
      @onClose="visiblBrande = false"
    />

    <!-- 品牌信息 -->
    <PreviewDetail
      :visible="visiblPreviewDetail"
      :id="detailId"
      @onClose="visiblPreviewDetail = false"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  createVNode,
  ref,
  toRefs,
  computed,
  watch,
  reactive,
  onMounted
} from "vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import {
  PlusOutlined,
  EllipsisOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import AddBrandCategory from "./modules/AddBrandCategory.vue";
import AddBrand from "./modules/AddBrand.vue";
import PreviewDetail from "./modules/PreviewDetail.vue";
import { Modal, message, Empty } from "ant-design-vue";
import BLCOMMON, { CustomTable } from "bl-common-vue3";
import dayjs from "dayjs";

export default defineComponent({
  name: "customerBrand",
  components: {
    PlusOutlined,
    AddBrandCategory,
    EllipsisOutlined,
    CustomTable,
    AddBrand,
    PreviewDetail,
  },
  setup() {
    //  分类按钮权限控制

    // 分类添加权限
    const isCategoryAdd = computed(() => {
      return BLCOMMON.utils.getBtnPermission([
        "customerBrandCategory",
        "curd",
        "categoryAdd",
      ]);
    });

    //  分类编辑权限
    const isCategoryEdit = computed(() => {
      return BLCOMMON.utils.getBtnPermission([
        "customerBrandCategory",
        "curd",
        "categoryEdit",
      ]);
    });

    // 分类删除权限
    const isCategoryDelete = computed(() => {
      return BLCOMMON.utils.getBtnPermission([
        "customerBrandCategory",
        "curd",
        "categoryDelete",
      ]);
    });

    // 导出名称
    const exportTitle = computed(() => {
      return "品牌库-" + dayjs().format("YYYYMMDDHHmmss");
    });

    const state = reactive({
      count: 0,
      selectedKeys: [0],
      treeData: [],
      spinning: false,
      visiblBrandeCategory: false,
      detailId: 0,
      fieldNames: {
        children: "son_list",
        title: "cat_name",
        key: "id",
      },
      brandeId: 0,
      columns: [
        {
          title: "品牌LOGO",
          dataIndex: "brand_logo",
          key: "brand_logo",
          columnType: "image",
          width: 100,
        },
        {
          title: "品牌名称",
          dataIndex: "brand_name",
          key: "brand_name",
          hasSort: true,
          search: {
            input_type: "input",
            search_type: "like",
          },
          width: 200,
        },
       
        {
          title: "业态",
          dataIndex: "brand_cat_name",
          key: "brand_cat_name",
          width: 180,
        },
        {
          title: "经营方式",
          dataIndex: "brand_info.operation_mode",
          key: "brand_info.operation_mode",
          width: 110,
        },
        {
          title: "品牌定位",
          dataIndex: "brand_info.position",
          key: "brand_info.position",
          columnType: "dictionary",
          dictType: "org_custom_brand_position",
          search: {
            input_type: "select",
            search_type: "equal",
          },
          width: 110,
        },
        {
          title: "合作日期",
          dataIndex: "partner_date",
          key: "partner_date",
          search: {
            input_type: "dateRangePicker",
            search_type: "between",
          },
          width: 100,
        },
        {
          title: "注册国家",
          dataIndex: "brand_info.reg_country",
          key: "brand_info.reg_country",
          columnType: "dictionary",
          dictType: "org_custom_brand_reg_country",
          width: 110,
        },
        {
          title: "人均消费",
          dataIndex: "brand_info.consumption",
          key: "brand_info.consumption",
          width: 110,
        },
        {
          title: "消费群体",
          dataIndex: "brand_info.consumer_group",
          key: "brand_info.consumer_group",
          width: 110,
        },
        {
          title: "最后跟进时间",
          dataIndex: "last_follow_time",
          key: "last_follow_time",
          hasSort: true,
          width: 130,
        },
        {
          title: "操作",
          dataIndex: "action",
          key: "action",
          fixed: "right",
          columnType: "operation",
          width: 120,
          buttons: [
            {
              name: "编辑",
              key: "edit",
              onClick: ({ record }) => {
                viewDetail(record.id);
              },
              props: {
                disabled: !BLCOMMON.utils.getBtnPermission([
                  "customerBrandCategory",
                  "curd",
                  "edit",
                ]),
              },
            },
            {
              name: "删除",
              key: "del",
              onClick: ({ record }) => {
                deleteClick(record.id);
              },
              props: {
                danger: true,
                disabled: !BLCOMMON.utils.getBtnPermission([
                  "customerBrandCategory",
                  "curd",
                  "delete",
                ]),
              },
            },
          ],
        },
      ],
      rightButtons: [
        {
          name: "新增",
          key: "add_brand",
          onClick: () => {
            addBrandCategory();
          },
          props: {
            type: "primary",
            disabled: !BLCOMMON.utils.getBtnPermission([
              "customerBrandCategory",
              "curd",
              "add",
            ]),
          },
        },
      ],

      visiblBrande: false,

      visiblPreviewDetail: false, //品牌信息抽屉

      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,

      filters:[],
      brand_search_info:{},
      tableHeight: 0
    });
    // tab表格实例
    const customTableRef = ref(null);

    const addBrand = () => {
      state.brandeId = 0;
      state.visiblBrandeCategory = true;
    };

    const successChange = () => {
      state.visiblBrandeCategory = false;
      getCategoryList();
    };

    const menuClick = (data, type) => {
      if (type == "edit") {
        state.brandeId = data;
        state.visiblBrandeCategory = true;
        return;
      }
      if (type == "delete") {
        Modal.confirm({
          title: `确认要删除【${data.cat_name}】吗？`,
          icon: createVNode(ExclamationCircleOutlined),
          onOk() {
            request
              .del("/org", `/org/brand/custom/brand/category/${data.id}`)
              .then((res) => {
                message.success("删除成功");
                if (data.id == state.selectedKeys[0]) {
                  state.selectedKeys = [0];
                  state.filters = []
                  state.brand_search_info = {}
                  customTableRef.value.loadData(true);
                }
                getCategoryList();
              });
          },
        });
      }
    };

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: () => {
          previewDetail(record.id);
        },
      };
    };

    const onSelect = (select, info) => {
      const { key, parent_id } = info.node;
      state.selectedKeys = [key];
      state.filters = [];
      // 二级分类
      if (parent_id) {
        state.brand_search_info.cat_fid = parent_id;
        state.brand_search_info.cat_id = key;
        state.filters.push(
          {
            field: "cat_id",
            type: "equal",
            value: state.brand_search_info.cat_id,
          },
          {
            field: "cat_fid",
            type: "equal",
            value: state.brand_search_info.cat_fid,
          }
        );
      } else {
        // 一级分类
        state.brand_search_info.cat_fid = key;
        state.brand_search_info.cat_id = undefined;
        state.filters.push({
          field: "cat_fid",
          type: "equal",
          value: state.brand_search_info.cat_fid,
        });
      }
      // 所有分类
      if (key == 0) {
        state.brand_search_info.cat_id = undefined;
        state.brand_search_info.cat_fid = undefined;
        state.filters = [];
      }

      customTableRef.value.loadData(true);
    };

    const getCategoryList = () => {
      state.spinning = true;
      request
        .post("/org", "/org/brand/custom/brand/category/query", { filters: [] })
        .then((res) => {
          state.spinning = false;
          state.treeData = res.list || [];
          state.treeData.unshift({
            cat_name: "所有分类",
            id: 0,
          });
        })
        .catch((err) => {
          state.spinning = false;
        });
    };

    getCategoryList();

    // 添加品牌
    const addBrandCategory = () => {
      state.detailId = 0;
      state.visiblBrande = true;
    };

    const successBrandChange = () => {
      state.visiblBrande = false;
      customTableRef.value.loadData(true);
    };

    // 查看
    const previewDetail = (id) => {
      state.detailId = id;
      state.visiblPreviewDetail = true;
    };

    // 编辑
    const viewDetail = (id) => {
      state.detailId = id;
      state.visiblBrande = true;
    };

    // 删除
    const deleteClick = (id) => {
      request.del("/org", `/org/brand/custom/brand/${id}`).then((res) => {
        message.success("删除成功");
        customTableRef.value.loadData(true);
      });
    };

    const rightRef = ref(null)

    onMounted(()=>{
      if (rightRef.value) {
        state.tableHeight = rightRef.value.clientHeight
      }
    })

    window.addEventListener('resize', ()=> {
      if (rightRef.value) {
        state.tableHeight = rightRef.value.clientHeight
      }
    })

    return {
      ...toRefs(state),
      addBrand,
      successChange,
      menuClick,
      customTableRef,
      onSelect,
      addBrandCategory,
      successBrandChange,
      previewDetail,
      viewDetail,
      deleteClick,
      customRow,
      isCategoryAdd,
      isCategoryEdit,
      isCategoryDelete,

      exportTitle,
      rightRef,
    };
  },
});
</script>

<style lang="less" scoped>
.customer-brand {
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;

  .left {
    min-width: 200px;
    height: 100%;
    background: #ffff;
    margin-right: 10px;
    flex-shrink: 0;

    .padding-5 {
      padding: 5px;
    }

    .plus-outlined {
      cursor: pointer;
      font-size: 12px;
    }

    .divider {
      margin: 0px;
    }

    .tree-content {
      height: calc(100% - 32px);
      overflow: hidden auto;
      .item-content {
        .ellipsis {
          opacity: 0;
        }
        &:hover {
          .ellipsis {
            opacity: 1;
          }
        }
      }
    }
  }

  .right {
    flex: 1;
    :deep(.ant-form-item) {
      margin: 0;
    }

    .sear-width {
      width: 230px;
    }
  }
}
</style>
